package com.example.baudusdk;




import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;

/**
 * @author: zouren
 * @date: 2021/5/29
 * @description:
 */
public class EntCoordSyncJob {
    static String AK = "ADeoDa4XSfz9yc0WRjU1bPs6lWFSWSK7"; // 百度地图密钥

    public static void main(String[] args) {
        String dom = "北京王府井";
        JSONObject coordinate = getCoordinate(dom);
        System.out.println("'" + dom + "'的经纬度为：" + coordinate);
        // System.err.println("######同步坐标已达到日配额6000限制，请明天再试！#####");
    }

    // 调用百度地图API根据地址，获取坐标

    public static JSONObject getCoordinate(String address) {
        if (address != null && !"".equals(address)) {
            //https://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi
            address = address.replaceAll("\\s*", "").replace("#", "栋");
            String url = "http://api.map.baidu.com/place/v2/search?query=" + address + "&region=264&output=json&coord_type=1&ak=" + AK;
            String json = loadJSON(url);
            if (json != null && !"".equals(json)) {
                JSONObject obj = JSONObject.parseObject(json);
                if ("0".equals(obj.getString("status"))) {
                    if(obj.getJSONArray("results")!=null&&obj.getJSONArray("results").size()>0){
                        JSONObject rs = obj.getJSONArray("results").getJSONObject(0);
                        JSONObject location = rs.getJSONObject("location");
                        return location;
                    }


//                    double lng = location.getDouble("lng"); // 经度
//                    double lat = location.getDouble("lat"); // 纬度
//                    DecimalFormat df = new DecimalFormat("#.######");
//                    return df.format(lng) + "," + df.format(lat);
                }
            }
        }
        return null;
    }

    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
        return json.toString();
    }
}
